<template>
	<view class="body">
		<image class="log" src="../../static/pic/banner1.png" mode=""></image>
		<view class="container">
			<input class="input" placeholder="请输入账号" type="text" @input="getUsername" />
			<input class="input" placeholder="请输入密码" type="text" @input="getPassWord" />
			<input class="input" placeholder="请再次确认密码" type="text" @input="getConfirmPwd" />
			<text class="to-register" @click="toLogin">去登陆</text>
			<button class="loginbtn" type="primary" @click="submit">注册</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		http
	} from '../../API/request.js';
	import {
		onLoad,
		onShow,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	const username = ref('')
	const password = ref('')
	const confirmpwd = ref('')
	const openid = ref('')
	const getUsername = (e) => {
		username.value = e.detail.value.trim()
	}
	const getPassWord = (e) => {
		password.value = e.detail.value.trim()
	}
	const getConfirmPwd = (e) => {
		confirmpwd.value = e.detail.value.trim()
	}
	const submit = () => {
		console.log(username.value)
		if (!username.value || !password.value || !confirmpwd.value) {
			uni.showToast({
				title: '存在未填项',
				icon: 'none'
			})
			return
		}
		if (password.value !== confirmpwd.value) {
			uni.showToast({
				title: '两次输入密码不一致',
				icon: 'none'
			})
			return
		}
		http.post('/register', {
			openid: openid.value,
			username: username.value,
			password: password.value,
		}).then((res) => {
			const {
				data
			} = res
			console.log(res)
			if (data === 'Registered') {
				uni.showToast({
					title: '此账号已被注册',
					icon: 'none'
				})
				return
			} else if (data === 'success') {
				uni.showToast({
						title: '注册成功',
						icon: 'none'
					}),
					uni.redirectTo({
						url: '/pages/Login/Login'
					})
			}
		})
	}
	const toLogin = () => {
		uni.redirectTo({
			url: '/pages/Login/Login'
		})
	}

	onLoad(() => {
		openid.value = uni.getStorageSync('openid')
		if (!openid) {
			uni.login({
				success: function(res) {
					if (res.code) {
						http.get('/login', {
							params: {
								code: res.code
							}
						}).then((res) => {
							const {
								data
							} = res
							if (data !== "error") {
								uni.setStorageSync('openid', data)
							}
						})
					} else {}
				}
			});
		}
	})
</script>

<style lang="less">
	.body {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 100rpx;
		height: 100vh;
		background-color: #fff;

		.log {
			width: 150rpx;
			height: 150rpx;
			border-radius: 50%;
		}

		.container {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-top: 100rpx;
			width: 70%;

			.input {
				width: 100%;
				border-bottom: 2rpx solid #aaa;
				margin-bottom: 40rpx;
			}

			.to-register {
				margin-right: auto;
				color: skyblue;

			}

			.loginbtn {
				width: 80% !important;
				margin-top: 80rpx;
			}
		}

	}
</style>